package client;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import event.Event;
import event.EventHandler;

public class PeerFileResponseEventHandler implements EventHandler {

	private final DownloadManager mDownloadManager;

	public PeerFileResponseEventHandler(DownloadManager manager) {
		mDownloadManager = manager;
	}

	@Override
	public void handle(Event e) {
		if (e.type == Event.FIL_TYPE) {
			String workingDir = new File("").getAbsolutePath();
			String[] p = e.parameters.split("DELIMETER");
			String remotePath = "";
			String shortPath = "";
			if (p.length > 1) {
				remotePath = p[0];
				shortPath = p[1];
			}

			int index = shortPath.lastIndexOf('/');
			String name = shortPath.substring(index + 1);

			String path = shortPath.substring(0, index);

			path = workingDir + path + "/";

			File file = new File(path + "." + name);

			if (!file.exists()) {
				new File(path).mkdirs(); // build the necessary
				// directories

				try {
					file.createNewFile();
				} catch (IOException ex) {

				}
			}

			Download download = null;

			/*
			 * If the offset is not 0, we are not on the first segment of the
			 * Event group; therefore append to the file.
			 */
			boolean appendMode = e.packageOffset > 0;

			download = mDownloadManager.getDownload(remotePath);
			if (download != null) {
				download.setlength(e.packageSize);
				
				byte[] message = e.message;

				try {
					FileOutputStream fos = new FileOutputStream(file,
							appendMode);

					appendFileSegment(fos, message);

					fos.flush();
					fos.close();

					if (message != null) {
						download.updateDownload(message.length);
					}
				} catch (IOException ex) {
					System.out
							.println("> An error occured in transferring the file.");
				} finally {
					/*
					 * Once the download is complete, un-hide the file.
					 */
					if (e.packageOffset + message.length >= e.packageSize) {
						if (file.renameTo(new File(path + name))) {

						}
					}
				}
			}
		}
	}

	private void appendFileSegment(OutputStream os, byte[] body)
			throws IOException {
		/*
		 * Open a file output stream in append mode.
		 */
		BufferedOutputStream bos = new BufferedOutputStream(os);

		// Write to the file.
		bos.write(body, 0, body.length);
		bos.flush();
		bos.close();
	}

}
